const { getOpenid, loginByOpenid } = require('../../utils/miniapp')

Page({
  data: {
    redirect: '',
    agreed: false,
    showAgreementModal: false
  },
  onLoad(options) {
    if (options && options.redirect) {
      this.setData({ redirect: decodeURIComponent(options.redirect) })
    }

    // 断开全局socket
    const app = getApp();
    if (app.socket) {
      try {
        app.socket.disconnect();
      } catch (e) {
        console.warn('socket disconnect error', e);
      }
      app.socket = null;
      app.globalData.isSocketConnect = false;
    }
  },
  /**
   * 切换协议同意状态
   */
  toggleAgreement() {
    this.setData({
      agreed: !this.data.agreed
    });
  },
  /**
   * 显示用户协议弹窗
   */
  showAgreement() {
    this.setData({
      showAgreementModal: true
    });
  },
  /**
   * 隐藏用户协议弹窗
   */
  hideAgreement() {
    this.setData({
      showAgreementModal: false
    });
  },
  onAuthLogin() {
    // 检查是否同意协议
    if (!this.data.agreed) {
      wx.showToast({
        title: '请先同意用户授权协议',
        icon: 'none'
      });
      return;
    }
    
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        const userInfo = res.userInfo;
        // 更新存储用户信息到缓存
        wx.setStorageSync('userInfo', userInfo)
        // TODO: Upload userInfo to your server
        console.log('User Info:', userInfo);
        wx.login({
          success: (res) => {
            if (res.code) {
              wx.showLoading({ title: '登录中', mask: true })
              // getOpenid会自动调用loginByOpenid
              getOpenid(res.code)
              // 由于miniapp.js的getOpenid和loginByOpenid没有回调，这里用定时器轮询token
              const checkToken = () => {
                const token = wx.getStorageSync('token')
                if (token) {
                  wx.hideLoading()
                  wx.showToast({ title: '登录成功' })
                  const redirect = this.data.redirect
                  if (redirect) {
                    // 通知app.js重连socket
                    const app = getApp();
                    if (app.socket) {
                      try {
                        app.socket.disconnect();
                      } catch (e) {}
                      app.socket = null;
                      app.globalData.isSocketConnect = false;
                    }
                    if (typeof app.reconnectSocket === 'function') {
                      app.reconnectSocket();
                    }
                    wx.redirectTo({ url: `/${redirect}` })
                  } else {
                    // 通知app.js重连socket
                    const app = getApp();
                    if (app.socket) {
                      try {
                        app.socket.disconnect();
                      } catch (e) {}
                      app.socket = null;
                      app.globalData.isSocketConnect = false;
                    }
                    if (typeof app.reconnectSocket === 'function') {
                      app.reconnectSocket();
                    }
                    wx.switchTab({ url: '/pages/finance/index/index' })
                  }
                } else {
                  setTimeout(checkToken, 300)
                }
              }
              checkToken()
            } else {
              wx.showToast({ title: '获取code失败', icon: 'none' })
            }
          },
          fail: () => {
            wx.showToast({ title: '微信登录失败', icon: 'none' })
          }
        })
      },
      fail: (err) => {
        console.error('getUserProfile failed:', err);
        wx.showToast({ title: '获取用户信息失败', icon: 'none' });
      }
    });
  }
}) 